#include "bsp_timer.h"

uint8_t timer_5ms_flag = 0;

uint16_t timer_200ms_cnt = 0;
uint8_t timer_200ms_flag = 0;

uint16_t timer_1s_cnt = 0;
uint16_t timer_500ms_cnt = 0;
uint16_t timer_3s_cnt = 0;
uint8_t timer_1s_flag = 0;
uint8_t timer_500ms_flag = 0;
uint8_t timer_3s_flag = 0;

/**
 * @brief 定时器3基础配置
*/
static void TIMER3_BaseConfiguration(void)
{
    timer_parameter_struct timer_initpara;

    rcu_periph_clock_enable(RCU_TIMER3);
    timer_deinit(TIMER3);
    timer_struct_para_init(&timer_initpara);
	
    timer_initpara.period = 100 * 5 - 1;        // 5ms
    timer_initpara.alignedmode = TIMER_COUNTER_EDGE;
    timer_initpara.counterdirection = TIMER_COUNTER_UP;
    timer_initpara.prescaler = 720 - 1;
    timer_initpara.clockdivision = TIMER_CKDIV_DIV1;
    timer_init(TIMER3, &timer_initpara);
    timer_interrupt_enable(TIMER3, TIMER_INT_FLAG_UP);
}

/**
 * @brief 使能
*/
static void TIMER3_NVIC_Configuration(void)
{
    nvic_irq_enable(TIMER3_IRQn, 5, 0);
}

/**
 * @brief 定时器3配汇总
*/
void TIMER3_Configuration(void)
{
    TIMER3_BaseConfiguration();
    TIMER3_NVIC_Configuration();
    timer_enable(TIMER3);
}

/*  */
void TIMER3_IRQHandler(void)
{
	timer_interrupt_flag_clear(TIMER3, TIMER_FLAG_UP);

	timer_5ms_flag = 1;

	if ((uart0_frame_end_flag == RECEIVING) || (uart0_frame_end_flag == WAITING))
	{
		uart0_frame_end_flag--;
	}

	timer_200ms_cnt++;
	timer_1s_cnt++;
	timer_3s_cnt++;
	timer_500ms_cnt++;
	if (TIMER_5MS_200MS == timer_200ms_cnt)
    {
		timer_200ms_cnt = 0;
		timer_200ms_flag = 1;
	}

	if (TIMER_5MS_1S == timer_1s_cnt)
    {
		timer_1s_cnt = 0;
		timer_1s_flag = 1;
		iwdg_feed();
		
		/* 连续10s收不到数据认为 CONNECT ERR, 显示背景 */
		if ((g_lcd_display_info.comm_state != ERR) && (g_lcd_manager.comm_disconnect_cnt++ >= 10))
		{
			g_lcd_manager.comm_disconnect_cnt = 0;
			g_lcd_display_info.comm_state = ERR;

			g_lcd_manager.lcd_event = REFRESH_BACK;
		}
	}
	
	if (TIMER_5MS_500MS == timer_500ms_cnt) {
		timer_500ms_cnt = 0;
		timer_500ms_flag = 1;
	}
	
	// if (TIMER_5MS_3S == timer_3s_cnt) {
	// 	timer_3s_cnt = 0;
	// 	timer_3s_flag = 1;
	// }

    if (key0.key_event == NONE)
	{
		key_val_get();
		key_event_get();
	}
}






